from moderation.models import Modification, ModelModification
from datetime import datetime
from django.contrib.contenttypes.models import ContentType
from django.utils import simplejson
from promisecheck.models import Promise
from django.db import models

def _dictkeystostring(d):
    d2 = {}
    for k,v in d.items():
        d2[str(k)]=v
    return d2

def put_to_moderation(user,
                      model,
                      action,
                      pk=None, values=None, form=None,
                      onaccept=None):
    mod = Modification(author=user,
                       time=datetime.now(),
                       url=None,
                       status=0)
    mod.save()
    cto = ContentType.objects.get_for_model(model)
    items = form.data.items()
    # if form.has_changed():
    changed_items = form.changed_data
    # take only changed items
    citems = dict([(k,v) for k,v in items if k in changed_items])
    items_json = simplejson.dumps(citems)
    mm = ModelModification(modification=mod,
                           content_type=cto,
                           action=0,
                           values=items_json,
                           onaccept=onaccept)
    mm.save()
    # adding
    #pf = Promise(**items)
    #pf.save()

def accept_modification(mod):
    for mm in mod.models.all():
        items = _dictkeystostring(simplejson.loads(mm.values))
        model = mm.content_type.model_class()
        for field in model._meta.fields:
            if isinstance(field, models.ForeignKey) and field.name in items:
                items['%s_%s' % (field.name, 'id')] = items.pop(field.name)
        oc = mm.content_type.model_class()(**items)
        oc.save()
        if not mm.onaccept:
            continue
        models_module = mm.content_type.model_class().__module__
        base_module = models_module.partition('.models')[0]
        utils_module = '%s.%s' % (base_module, 'utils')
        i=__import__(utils_module, globals(), locals(),[mm.onaccept])
        i.__dict__[mm.onaccept](oc)
    mod.status=1
    mod.save()
